﻿using System;
using Demo.Identity.Dto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Demo.Identity;

/// <summary>
/// 自定义登录异常
/// </summary>
public class LoginException : Exception
{
    /// <summary>
    /// 自定义登录异常
    /// </summary>
    /// <param name="message">异常信息</param>
    public LoginException(string message) : base(message)
    {
    }
}

/// <summary>
/// 登录异常过滤器
/// </summary>
public class LoginExceptionFilter : ExceptionFilterAttribute
{
    /// <summary>
    /// 自定义登录异常处理
    /// </summary>
    /// <param name="context"></param>
    public override void OnException(ExceptionContext context)
    {
        if (context.Exception is LoginException)
        {
            context.Result = new JsonResult(
                new LoginResponse
                {
                    HasError = true,
                    Message = context.Exception.Message
                }
            )
            {
                StatusCode = 401
            };
            context.ExceptionHandled = true;
        }
    }
}